var geocoder;
var map;
var markersArray = [];
var address;
var marker = '';
directionsGraph = {};

window.onload = function initialize() {
	geocoder = new google.maps.Geocoder();
	var latlng = new google.maps.LatLng(50.060, 19.959);
	var mapOptions = {
		zoom : 13,
		center : latlng
	};
	map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
	codeAddress();
};

	
function codeAddress() {
	var table = $('.address');
	
	table.each(function(){
		var address = $(this).val();
		var name = $(this).closest('.pair').find('.names').val();
		geocoder.geocode({
			'address' : address
		},
		function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				map.setCenter(results[0].geometry.location);
				var contentString = '<h3>'+name+'</h3><p>' + address + '<p>';
				var infowindow = new google.maps.InfoWindow({
					content : contentString,
					maxWidth : 200
				});

				var marker = new google.maps.Marker({
					map: map,
					position: results[0].geometry.location,
					title: name
				});
				markersArray.push( marker );

				google.maps.event.addListener(marker, 'click', function() {
					infowindow.open(map, marker);
				});
			} else {
				alert("Nie udało się wygenerować mapy: " + status);
			}
		});
	});
}

function showAddress() {
	var pinColor = "00FF00";
    var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
	        new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34));
	
    var address = document.getElementById("adres").value;
    
    geocoder.geocode( { 'address': address}, function(results, status) {
    	if (status == google.maps.GeocoderStatus.OK) {
    		map.setCenter(results[0].geometry.location);
    		var marker = new google.maps.Marker({
    			map: map,
    			position: results[0].geometry.location,
    			title: address,
    			icon: pinImage
    		});
    	} else {
    		alert("Nie udało się wygenerować mapy: " + status);
    	}
    });
}
  
function showAutomat() {
	if( marker != '' ) {
		marker.setMap(null);
	}
	
	var pinColor = "00FF00";
	var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
	    new google.maps.Size(21, 34), new google.maps.Point(0,0), new google.maps.Point(10, 34));
	address = document.getElementById("automat").value;
	geocoder.geocode( { 'address': address}, function(results, status) {
		if( status == google.maps.GeocoderStatus.OK ){
			map.setCenter(results[0].geometry.location);
			marker = new google.maps.Marker({
				map: map,
			    position: results[0].geometry.location,
			    title: address,
		        icon: pinImage
		    });
		} else {
			alert("Nie udało się wygenerować mapy: " + status);
		}
	});
}